//
//  TestViewController8.m
//  MSDemo
//
//  Created by ms on 2024/3/15.
//

#import "TestViewController8.h"
#import "SearchViewController.h"

@interface TestViewController8 ()
<
UITableViewDelegate,
UITableViewDataSource
>

@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) UIButton *addItemBtn;
@property (nonatomic, strong) UITableView *cateTableView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ItemViewModel *viewModel;

@end

@implementation TestViewController8

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"商品进销存管理";
}

- (void)ms_bindViewModel
{
    ms_weakSelf;
    [[self.viewModel.addItemCateCommand.executing skip:1] subscribeNext:^(NSNumber * _Nullable x) {
       
        if ([x isEqualToNumber:@YES])
        {
            ms_showHud(self.view, @"", NO);
        }
        else
        {
            ms_hideHud(self.view);
        }
    }];
    [[self.viewModel.addItemCommand.executing skip:1] subscribeNext:^(NSNumber * _Nullable x) {
       
        if ([x isEqualToNumber:@YES])
        {
            ms_showHud(self.view, @"", NO);
        }
        else
        {
            ms_hideHud(self.view);
        }
    }];
    [self.viewModel.refreshUISubject subscribeNext:^(id  _Nullable x) {
        
        ms_strongSelf
        switch ([x integerValue])
        {
            case MSRefreshUI:
            {
                [self.cateTableView reloadData];
                [self.tableView reloadData];
            }
                break;
                
            default:
                break;
        }
    }];
}


#pragma mark - event
- (void)search
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}
- (void)addCate
{
    ItemCateModel *model = [[ItemCateModel alloc] init];
    model.name = @"衣服";
    self.viewModel.addItemCateModel = model;
    [self.viewModel.addItemCateCommand execute:nil];
}
- (void)addItem
{
    ItemCateModel *cateModel = self.viewModel.itemCateModels.firstObject;
    ItemModel *model = [[ItemModel alloc] init];
    model.name = @"商品名";
    model.image = UIImagePNGRepresentation(MS_IMAGE_NAMED(@"Image"));
    model.introduce = @"商品介绍";
    model.expirationTime = 1724983200;
    model.catePk = cateModel.pk;
    model.cateName = cateModel.name;
    model.line = @1;
    model.number = @123456;
    model.addTime = 1719453600;
    model.addTime = 1719453600;
    model.isDel = NO;
    
    self.viewModel.addItemModel = model;
    [self.viewModel.addItemCommand execute:nil];
}


#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.cateTableView])
    {
        return self.viewModel.itemCateModels.count;
    }
    else
    {
        return self.viewModel.itemModels.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.cateTableView])
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cateCell"];
        cell.textLabel.text = self.viewModel.itemCateModels[indexPath.row].name;
        
        return cell;
    }
    else
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"itemCell"];
        
        ItemModel *model = self.viewModel.itemModels[indexPath.row];
        cell.imageView.image = [UIImage imageWithData:model.image];
        cell.textLabel.text = model.name;
        cell.detailTextLabel.text = model.introduce;
        
        return cell;
    }
}


#pragma mark - UI
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
}
- (void)updateViewConstraints
{
    [super updateViewConstraints];
    [self.searchBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(88);
        make.height.mas_equalTo(44);
        make.centerY.equalTo(self.navBar.titleLabel);
    }];
    [self.cateTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.navBar.mas_bottom);
        make.left.equalTo(self.view);
        make.bottom.mas_equalTo(-MS_SAFE_AREA_BOTTOM_HEIGHT);
        make.width.mas_equalTo(200 * MS_ADAPTATION_RATIO);
    }];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.navBar.mas_bottom);
        make.left.equalTo(self.cateTableView.mas_right);
        make.right.equalTo(self.view);
        make.bottom.mas_equalTo(-MS_SAFE_AREA_BOTTOM_HEIGHT);
    }];
    [self.addItemBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.mas_equalTo(-MS_SAFE_AREA_BOTTOM_HEIGHT - 30);
        make.width.mas_equalTo(88);
        make.height.mas_equalTo(88);
        make.centerX.equalTo(self.view);
    }];
}
- (void)ms_addSubviews
{
    [self.navBar addSubview:self.searchBtn];
    [self.view addSubview:self.cateTableView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.addItemBtn];
}


#pragma mark - getter
- (UIButton *)searchBtn
{
    if (!_searchBtn)
    {
        _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_searchBtn setTitle:@"搜索"
                    forState:UIControlStateNormal];
        [_searchBtn setTitleColor:MS_HEX_COLOR(0x333333)
                         forState:UIControlStateNormal];
    }
    
    return _searchBtn;
}
- (UIButton *)addItemBtn
{
    if (!_addItemBtn)
    {
        _addItemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _addItemBtn.alpha = 0.5;
        _addItemBtn.backgroundColor = MS_HEX_COLOR_AND_ALPHA(0x666666, 0.7);
        _addItemBtn.titleLabel.numberOfLines = 0;
        [_addItemBtn setTitle:@"添加\n商品"
                    forState:UIControlStateNormal];
        [_addItemBtn setTitleColor:MS_HEX_COLOR(0x333333)
                         forState:UIControlStateNormal];
        _addItemBtn.titleLabel.font = MS_BOLD_SYSTEM_FONT_OF_SIZE(15);
        [_addItemBtn addTarget:self
                       action:@selector(addItem)
             forControlEvents:UIControlEventTouchUpInside];
        [_addItemBtn ms_makeChains:^(MSChainMaker * _Nonnull make) {
            
            make.ms_cornerRadii(44);
        }];
    }
    
    return _addItemBtn;
}
- (UITableView *)cateTableView
{
    if (!_cateTableView)
    {
        _cateTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _cateTableView.dataSource = self;
        _cateTableView.delegate = self;
        _cateTableView.rowHeight = 44;
        _cateTableView.showsVerticalScrollIndicator = NO;
        [_cateTableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"cateCell"];
    }
    
    return _cateTableView;
}
- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 100;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"itemCell"];
    }
    
    return _tableView;
}
- (ItemViewModel *)viewModel
{
    if (!_viewModel)
    {
        _viewModel = [[ItemViewModel alloc] init];
    }
    
    return _viewModel;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

@implementation ItemCateModel


@end

@implementation ItemModel



@end

@implementation ItemViewModel

- (void)ms_initialize
{
    self.itemModels = [NSMutableArray arrayWithArray:[ItemModel ms_findAll]];
    self.itemCateModels = [NSMutableArray arrayWithArray:[ItemCateModel ms_findAll]];
}
- (RACCommand *)addItemCateCommand
{
    if (!_addItemCateCommand)
    {
        _addItemCateCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                if (![ItemCateModel ms_isExistInTable])
                {
                    [ItemCateModel ms_createTable];
                }
                
                if ([self.addItemCateModel ms_saveOrUpdate])
                {
                    [self.itemCateModels addObject:self.addItemCateModel];
                    [self.refreshUISubject sendNext:@(MSRefreshUI)];
                }
                else
                {
                    [self.refreshUISubject sendNext:@(MSRefreshError)];
                }
                
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                
                return [RACDisposable disposableWithBlock:^{
                    
                }];
            }];
        }];
    }
    
    return _addItemCateCommand;
}
- (RACCommand *)delItemCateCommand
{
    if (!_delItemCateCommand)
    {
        _delItemCateCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                if (![ItemCateModel ms_isExistInTable])
                {
                    [ItemCateModel ms_createTable];
                }
                
                if ([self.addItemCateModel ms_deleteObject])
                {
                    
                    [self.refreshUISubject sendNext:@(MSRefreshUI)];
                }
                else
                {
                    [self.refreshUISubject sendNext:@(MSRefreshError)];
                }
                
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                
                return [RACDisposable disposableWithBlock:^{
                    
                }];
            }];
        }];
    }
    
    return _delItemCateCommand;
}
- (RACCommand *)addItemCommand
{
    if (!_addItemCommand)
    {
        _addItemCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
//                if (![ItemModel ms_isExistInTable])
//                {
                    [ItemModel ms_createTable];
//                }
                
                if ([self.addItemModel ms_saveOrUpdate])
                {
                    [self.itemModels addObject:self.addItemModel];
                    [self.refreshUISubject sendNext:@(MSRefreshUI)];
                }
                else
                {
                    [self.refreshUISubject sendNext:@(MSRefreshError)];
                }
                
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                
                return [RACDisposable disposableWithBlock:^{
                    
                }];
            }];
        }];
    }
    
    return _addItemCommand;
}
- (RACCommand *)delItemCommand
{
    if (!_delItemCommand)
    {
        _delItemCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                if (![ItemModel ms_isExistInTable])
                {
                    [ItemModel ms_createTable];
                }
                
                if ([self.addItemModel ms_deleteObject])
                {
                    [self.refreshUISubject sendNext:@(MSRefreshUI)];
                }
                else
                {
                    [self.refreshUISubject sendNext:@(MSRefreshError)];
                }
                
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                
                return [RACDisposable disposableWithBlock:^{
                    
                }];
            }];
        }];
    }
    
    return _delItemCommand;
}

@end


@interface ItemCateView ()

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) ItemViewModel *viewModel;

@end

@implementation ItemCateView

- (instancetype)initWithViewModel:(id<MSViewModelProtocol>)viewModel
{
    self.viewModel = viewModel;
    
    return [super initWithViewModel:viewModel];
}


#pragma mark - event
- (void)textFieldDidChanged:(UITextField *)textField
{
    
}


#pragma mark - UI
- (void)layoutSubviews
{
    [super layoutSubviews];
}
- (void)updateConstraints
{
    [super updateConstraints];
}
- (void)ms_addSubviews
{
    
}


#pragma mark - getter
- (UILabel *)titleLabel
{
    if (!_titleLabel)
    {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = MS_SYSTEM_FONT_OF_SIZE(15);
        _titleLabel.textColor = MS_HEX_COLOR(0x333333);
        _titleLabel.text = @"添加分类";
    }
    
    return _titleLabel;
}
- (UITextField *)textField
{
    if (!_textField)
    {
        _textField = [[UITextField alloc] init];
        _textField.font = MS_SYSTEM_FONT_OF_SIZE(13);
        _textField.textColor = MS_HEX_COLOR(0x333333);
        _textField.placeholder = @"请输入分类名称";
        [_textField addTarget:self
                       action:@selector(textFieldDidChanged:)
             forControlEvents:UIControlEventEditingChanged];
    }
    
    return _textField;
}

@end
